/* 
	PROJECT: scsu-csc653-chatter
	ABOUT: handles accepting input stream from server, and notifying any listeners of input data
	DATE: 09-2010
	AUTHORS: skenny214@gmail.com, jinhongli08@gmail.com, hourigan.brian@gmail.com, yaqiluo2010@gmail.com
*/

package chatter.client;

import java.io.DataInput;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

public class ChatterClientInputStream extends Thread {
	//create our multiple levels of input readers
	InputStream input;
	DataInput dinput;
	
	//create a collection of input listeners
	ArrayList<IChatterClientInputListener> chatterClientInputListeners = new ArrayList<IChatterClientInputListener>();
	
	//constructor which takes a basic input stream and build it up into a buffered reader
	public ChatterClientInputStream(InputStream input){
		this.input = input;
		this.dinput = new DataInputStream(this.input);
	}
	
	//adds a new listener to the input stream listeners collection
	public void addChatterClientInputListenter(IChatterClientInputListener listener){
		this.chatterClientInputListeners.add(listener);
	}
	
	//removes a listeners from the input stream listeners collection
	public void removeChatterClientInputListener(IChatterClientInputListener listener){
		this.chatterClientInputListeners.remove(listener);
	}
	
	
	//the main thread run method - allow for nonblocking reading of other possible threads
	public void run(){
		while(true){
			try {
				String line= this.dinput.readUTF();
				if(ChatterClientApplet.isDebug) System.out.println("Received: "+line+", from server");
				
				this.fireChatterClientInputEvent(line);
				
			} catch (IOException e) {
				e.printStackTrace();
				//we hit an exception, most likely a disconnect...but either way we must be done with this loop
				//simulate a kicked event
				this.fireChatterClientInputEvent("%%Operation=logout%%status=success");
				break;
			}
		}
	}
	
	//calls this method to notify all listeners that we have an input event
	protected void fireChatterClientInputEvent(String line){
		for(IChatterClientInputListener listener : this.chatterClientInputListeners) {
			listener.onClientInput(new ClientInputEvent(this, line));
		}
	}
	
}
